package com.heima.controller;

import com.heima.domain.User;
import com.heima.model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserAddServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userName, password, sex, email;
        UserDao dao = new UserDao();
        User user = null;
        int result = 0;
        PrintWriter pw = null;

        //1.调用请求对象，读取请求头内的参数信息，得到用户的注册信息
        userName = request.getParameter("userName");
        password = request.getParameter("password");
        sex = request.getParameter("sex");
        email = request.getParameter("email");

        //2.调用UserDao，将用户信息填充到insert指令并借助jdbc规范发送到数据库服务器中
        user = new User(null, userName, password, sex, email);
        result = dao.add(user);

        //3.调用响应对象，将处理结果以二进制形式写入到响应体中
        response.setContentType("text/html;charset=utf-8");
        pw = response.getWriter();
        if (result == 1) {
            //pw.print("<center><font style='color:green;font-size:40'>会员注册成功</font></br>");
            //pw.print("<h1><a href='/web02/login.jsp'>现在登录</a></h1></center>");

            //登录成功
            //向request域中保存一个信息
            request.setAttribute("msg", "注册成功，开始登录吧！");

            //使用请求转发进行页面跳转
            request.getRequestDispatcher("/login.jsp").forward(request, response);

        } else {

            //登录失败
            //向request域中保存一个信息
            request.setAttribute("msg", "注册失败，换个用户名试试？");

            //使用请求转发进行页面跳转
            request.getRequestDispatcher("/user_add.jsp").forward(request, response);
            //pw.print("<center><font style='color:red;font-size:40'>会员注册失败，换个会员名试试？</font>");
            //pw.print("<a href='/web02/user_Add.html'>重新注册</a></center>");
        }

        //tomcat负责销毁请求对象和响应对象
        //tomcat负责将http相应协议包推送到发送请求得到浏览器中
        //浏览器根据响应头content-type指定的编译器对响应体二进制内容进行解析
        //浏览器将解析后的结果展示给用户 【结束】

    }
}
